package com.nova.android.tvlauncher.ext

import android.R.attr.action
import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.view.View
import com_github_lib_base.ext.lastClickTime

/**
 * 为 View 添加防抖点击事件，点击时先执行缩小-还原动画，然后执行回调
 *
 * @param interval 防抖间隔（毫秒，默认 500ms）
 * @param shrinkScale 动画缩小的比例（默认 0.8f）
 * @param animDuration 动画总时长（默认 300ms，缩小和还原各占一半）
 * @param action 点击动画结束后的回调
 */
fun View.clickNoRepeatWithAnim(
    interval: Long = 500,
    shrinkScale: Float = 1.1f,
    animDuration: Long = 350,
    delayTime: Long = 250,
    action: (view: View) -> Unit
) {


    setOnClickListener {
        val currentTime = System.currentTimeMillis()
        if (lastClickTime != 0L && (currentTime - lastClickTime < interval)) {
            return@setOnClickListener // 防抖，忽略快速点击
        }
        lastClickTime = currentTime

        // 创建缩小动画
        val scaleDownX = ObjectAnimator.ofFloat(it, View.SCALE_X, it.currentScaleX, shrinkScale)
        val scaleDownY = ObjectAnimator.ofFloat(it, View.SCALE_Y, it.currentScaleY, shrinkScale)
        // 创建还原动画
        val scaleUpX = ObjectAnimator.ofFloat(it, View.SCALE_X, shrinkScale, it.currentScaleX)
        val scaleUpY = ObjectAnimator.ofFloat(it, View.SCALE_Y, shrinkScale, it.currentScaleY)

        // 按顺序播放缩小和还原动画
        AnimatorSet().apply {
            playSequentially(
                AnimatorSet().apply { playTogether(scaleDownX, scaleDownY) },
                AnimatorSet().apply { playTogether(scaleUpX, scaleUpY) }
            )
            duration = animDuration / 2 // 缩小和还原各占一半时长
            addListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(animation: Animator) {}
                override fun onAnimationEnd(animation: Animator) {
                    handler.postDelayed({
                        action(it) // 动画结束时执行点击回调
                    },delayTime)

                }
                override fun onAnimationCancel(animation: Animator) {}
                override fun onAnimationRepeat(animation: Animator) {}
            })
            start()
        }
    }

    // 确保 View 可聚焦以接收点击事件
    isFocusable = true
    isFocusableInTouchMode = true
}

/**
 * 获取 View 当前的缩放比例
 */
private val View.currentScaleX: Float
    get() = scaleX

private val View.currentScaleY: Float
    get() = scaleY

